
var prefix = "/userAunt";
let checkId = JSON.parse(sessionStorage.getItem('matronId'));
$(function (){
    const stra = `<div style="margin-bottom: 10px;display: table" class="newSet"><div class="layui-form-item formfixed">
                <div class="taskName col-sm-6" style="padding-left: 0">
                    <input class="form-control startTime" type="text" placeholder="请输入工作开始时间">
                </div>
                <div class="taskScore col-sm-6" style="padding: 0">
                    <input class="form-control endTime" type="text" placeholder="请输入工作结束时间">
                </div>
                    <div class="remove col-sm-2">删除</div>
            </div>
            <div class="taskDesc col-sm-12" style="padding: 0">
                <textarea name="description" class="form-control description" type="text" placeholder="请输入工作描述"></textarea>
            </div></div>`;

    $("#addList").click(function (){
        $("#addBox").append(stra);
        layui.use(['laydate'],function(){
            let laydate = layui.laydate;
            lay('.startTime').each(function(){
                laydate.render({
                    elem: this
                    ,trigger: 'click'
                    // ,range: true
                });
            });

            lay('.endTime').each(function(){
                laydate.render({
                    elem: this
                    ,trigger: 'click'
                    // ,range: true
                });
            });
        })
    })

    $("body").on('click','.remove',function (){
        $(this).parents('.newSet').remove();
    })
})

layui.use(['form', 'xmSelect','upload'], function(){
    var form = layui.form;
    var layer = layui.layer;
    var xmSelect = layui.xmSelect, upload = layui.upload;
    var loading;
    let datas = [];

    $.get('/js/webJs/jzweb/jazUserAunt/data.json',function (data){
        let str = '';
        datas = data;
        data.map(function (v,k){
            if( k == 0 ) str += `<option value="">请选择</option>`;
            str += `<option value="${v.name}" >${v.name}</option>`;
        })
        $("#province").html(str)

        let string = '';
        datas.map(function (v){
            v.city.map(function (val){
                string += `<option value="${val.name}" >${val.name}</option>`;
            })
        })
        $("#city").html(string)

        let district = '';
        datas.map(function (v){
            v.city.map(function (val){
                val.area.map(function (item){
                    district += `<option value="${item}" >${item}</option>`;
                })
            })
        })
        $("#district").html(district)

        form.render();
    })

    form.on('select(province)', function(data){
        let string = '';
        datas.map(function (v){
            if( v.name == data.value ){
                v.city.map(function (val){
                    string += `<option value="${val.name}" >${val.name}</option>`;
                })
            }
        })
        $("#city").html(string).attr('disabled',false)
        form.render();
    });

    form.on('select(city)', function(data){
        let district = '';

        datas.map(function (v){
            v.city.map(function (val){
                if( val.name == data.value ){
                    val.area.map(function (item){
                        district += `<option value="${item}" >${item}</option>`;
                    })
                }
            })
        })
        $("#district").html(district).attr('disabled',false)
        form.render();
    });

    //同时绑定多个元素，并将属性设定在元素上
    upload.render({
        elem: '.uploadSend'
        ,multiple:'true'
        ,before: function(){
            loading = layer.load({
                type:3,
                content:'加载中...',
            });//在post之前定义loading
        }
        ,done: function(res){
            layer.close(loading);
            if( res.code == 0 ){
                let that = this;
                changBackfill(res,that);
            }else{
                layer.msg('上传失败,请检查');
            }

        }
        ,error:function (res){
            layer.msg(res.msg)
        }
    })

    var type = xmSelect.render({
        el: '#type',
        name:'type',
        layVerify:'typeThod',
        max: 3,
        maxMethod(seles, item){
            layer.msg('最大只能选择3个')
        },
        data: [],
    })
    // 服务类型
    const types = [];
    AjaxGet(prefix+'/seleProject').then(function (response){
        response.data.map(function (v){
            types.push({
                name:v.name,
                value:v.id
            })
        });
    }).catch(function (error){
        layer.msg(error.msg)
    })

    // 人物标签
    var tips = xmSelect.render({
        el: '#tips',
        name:'describe',
        layVerify:'tips',
        max: 3,
        maxMethod(seles, item){
            layer.msg('最多只能选择3个')
        },
        data: [],
    })

    const tipsr = [];
    AjaxGet(prefix+'/seleLabel').then(function (response){
        response.data.map(function (v){
            tipsr.push({
                name:v.describe,
                value:v.id
            })
        });
    }).catch(function (error){
        layer.msg(error.msg)
    })

    //自定义验证规则
    form.verify({
        name: function(value, item){
            if(!new RegExp("^[a-zA-Z0-9_\u4e00-\u9fa5\\s·]+$").test(value)){
                return '用户名不能有特殊字符';
            }
            if(/(^\_)|(\__)|(\_+$)/.test(value)){
                return '用户名首尾不能出现下划线\'_\'';
            }
            if(/^\d+\d+\d$/.test(value)){
                return '用户名不能全为数字';
            }
        },
        typeThod:function (value, item){
            if( !value ){
                return '请选择项目类型'
            }
        },
        phone: function(value){
            if(value.length < 11){
                const telStr = /^[1](([3][0-9])|([4][0,1,4-9])|([5][0-3,5-9])|([6][2,5,6,7])|([7][0-8])|([8][0-9])|([9][0-3,5-9]))[0-9]{8}$/;
                if (!(telStr.test(value))) {
                    return "手机号码输入不规范";
                }
            }
        },
        nativePlace:function (value, item){
            if( !value ){
                return '请输入籍贯'
            }
        },
        age:function (value, item){
            if( !value ){
                return '请输入年龄'
            }
        },
        sex:function (value, item){
            if( !value ){
                return '请选择性别'
            }
        },
        zodiac:function (value, item){
            if( !value ){
                return '请选择生肖'
            }
        },
        constellation:function (value, item){
            if( !value ){
                return '请选择星座'
            }
        },
        maritalStatus:function (value, item){
            if( !value ){
                return '请选择婚姻状况'
            }
        },
        education:function (value, item){
            if( !value ){
                return '请输入学历'
            }
        },
        height:function (value, item){
            if( !value ){
                return '请输入身高'
            }
        },
        weight:function (value, item){
            if( !value ){
                return '请输入体重'
            }
        },
        detailedAddress:function (value, item){
            if( !value ){
                return '请输入居住地址'
            }
        },
        tips:function (value, item){
            if( !value ){
                return '请选择标签'
            }
        },
        introduction:function (value, item){
            if( !value ){
                return '请输入自我介绍'
            }
        },
        residentHome:function (value, item){
            if( !value ){
                return '请选择驻家'
            }
        },
        desireSalary:function (value, item){
            if( !value ){
                return '请输入期望工资'
            }
        },
        workExperience:function (value, item){
            if( !value ){
                return '请输入工作经验'
            }
        },
        skill:function (value, item){
            if( !value ){
                return '请输入个人技能'
            }
        },
        experience:function (value, item){
            if( !value ){
                return '请输入工作经历'
            }
        },
        inchPhoto:function (value, item){
            if( !value ){
                return '请上传寸照'
            }
        },
        idPhotoFront:function (value, item){
            if( !value ){
                return '请上传身份证正面照'
            }
        },
        idPhotoSide:function (value, item){
            if( !value ){
                return '请上传身份证反面照'
            }
        },
        lifePhoto:function (value, item){
            if( !value ){
                return '请上传工作/生活照'
            }
        },
        certificate:function (value, item){
            if( !value ){
                return '请上传技能证书'
            }
        },
        report:function (value, item){
            if( !value ){
                return '请上传体检报告'
            }
        },
        showStatus:function (value, item){
            if( !value ){
                return '请选择展示状态'
            }
        },
        province:function (value, item){
            if( !value ){
                return '请选择省'
            }
        },
        city:function (value, item){
            if( !value ){
                return '请选择市'
            }
        },
        district:function (value, item){
            if( !value ){
                return '请选择区'
            }
        },
    });
    console.log(checkId)
    AjaxGet( '/userAunt/getUserAuntById' , {id:checkId.id} ).then(function (response){
        let userInfo = response.data.userDO;  //用户
        let matron = response.data.jazUserAuntDO;  // 月嫂

        $("#username").val(userInfo.name || '' ); //用户名字
        $("#mobile").val(userInfo.orderPhone || ''); //用户电话
        $("#nativePlace").val( userInfo.nativePlace || '' ); // 籍贯
        $("#age").val( userInfo.age  || ''); // 年龄
        $("#sex").val( userInfo.sex ); // 性别
        $("#zodiac").val( userInfo.zodiac || '' ); // 生肖
        $("#constellation").val( userInfo.constellation || '' ); // 星座
        $("#maritalStatus").val( userInfo.maritalStatus  || ''); // 婚姻
        $("#education").val( userInfo.education || '' ); // 学历
        $("#height").val( userInfo.height || '' ); // 身高
        $("#weight").val( userInfo.weight || '' ); // 体重

        $("#province").val( userInfo.province ); //省
        $("#city").val( userInfo.city ); //市
        $("#district").val( userInfo.district ); //区

        $("#detailedAddress").val( userInfo.detailedAddress); // 现住址
        // $("#detailedAddress").val(userInfo?.province == userInfo?.city ? `${userInfo?.city}${userInfo?.district}${userInfo?.detailedAddress}` :
        //     `${userInfo?.province}${userInfo?.city}${userInfo?.district}${userInfo?.detailedAddress}`); // 现住址

        $("#time").val( matron.createTime  || ''); // 时间
        $("#introduction").val( matron.introduction  || ''); // 自我介绍
        $("#residentHome").val( matron.residentHome ); // 是否住家
        $("#desireSalary").val( matron.desireSalary || '' ); // 期望工资
        $("#workExperience").val( matron.workExperience || ''); // 工作经验
        // $("#skill").val( matron.skill  || ''); // 个人技能
        // $("#experience").val( matron.experience || '' ); // 工作经历

        // let skill = JSON.parse(matron.skill);
        $("#serveTotal").val(matron.serveTotal);
        xmSelect.render({
            el: '#examinationCondition',
            name:'examinationCondition',
            layVerify:'examinationCondition',
            initValue:matron.examinationCondition.split(','),
            data: [
                {name: '技能考核合格', value: '技能考核合格'},
                {name: '理论考试合格', value: '理论考试合格'},
                {name: '服务礼仪合格', value: '服务礼仪合格'},
            ],
        })
        // 护理内容
        xmSelect.render({
            el: '#nurseContent',
            name:'nurseContent',
            layVerify:'nurseContent',
            initValue:matron.nurseContent.split(','),
            data: [
                {name: '产妇常规护理', value: '产妇常规护理'},
                {name: '新生儿常规护理', value: '新生儿常规护理'},
                {name: '双胎护理经验', value: '双胎护理经验'},
                {name: '早产儿护理经验', value: '早产儿护理经验'}
            ],
        })

        // 服务技能
        xmSelect.render({
            el: '#skill',
            name:'skill',
            layVerify:'skill',
            initValue:matron.skill.split(','),
            data: [
                {name: '营养月子餐', value: '营养月子餐'},
                {name: '母乳喂养指导', value: '母乳喂养指导'},
                {name: '产后恢复指导', value: '产后恢复指导'},
                {name: '个性化定制', value: '个性化定制'}
            ],
        })
        if(matron.experience) {
            let experience = JSON.parse(matron.experience),srr = '';
            experience?.map(function (v){
                srr += `
                    <div class="layui-form-item formfixed">
                        <div class="taskName col-sm-6" style="padding-left: 0">
                            <input class="form-control startTime" type="text" placeholder="请输入工作开始时间" value="${v.startTime}">
                        </div>
                        <div class="taskScore col-sm-6" style="padding: 0">
                            <input class="form-control endTime" type="text" placeholder="请输入工作结束时间" value="${v.endTime}">
                        </div>
                        <div class="remove col-sm-2" >删除</div>
                    </div>
                    <div class="taskDesc col-sm-12" style="padding: 0">
                        <textarea name="description" class="form-control description" type="text" placeholder="请输入工作描述">${v.describe}</textarea>
                    </div>`;
            })
            srr += `<div id="addBox"></div>`;
            $(".parseInset").html(srr);
        }

        $("#order").val( matron.orderCount || '' ); // 订单数
        $("#recharge").val(response.data.jazSysProject || '')

        // 服务类型
        let projectId = matron.projectId.split(',');
        types?.map(function (val){
            val.selected = false;
            projectId?.forEach(function (v){
                if( val.value == v ){
                    val.selected = true
                }
            })
        })

        type.update({
            data: types,
            autoRow: true,
        })

        //个人标签
        let str = '';

        tipsr?.forEach(function (val){
            val.selected = false;
            response.data.jazSysLabelDO?.forEach(function (v){
                if( val.value == v.id ){
                    val.selected = true
                }
            })
        })

        tips.update({
            data: tipsr,
            autoRow: true,
        })

        //寸照
        $("#inchPhoto").html(`<div class="layui-inline"><img class="upImg" width="100" src="${matron.inchPhoto || ''}"><img class="closeUpload" src="../../img/close.png" data-id="inchPhoto"></div>`);
        $("input[name='inchPhoto']").val(matron.inchPhoto);
        //身份证正面
        $("#idPhotoFront").html(`<div class="layui-inline"><img class="upImg" width="100" src="${matron.idPhotoFront || ''}"><img class="closeUpload" src="../../img/close.png" data-id="idPhotoFront"></div>`);
        $("input[name='idPhotoFront']").val(matron.idPhotoFront);
        //身份证反面
        $("#idPhotoSide").html(`<div class="layui-inline"><img class="upImg" width="100" src="${matron.idPhotoSide || ''}"><img class="closeUpload" src="../../img/close.png" data-id="idPhotoSide"></div>`);
        $("input[name='idPhotoSide']").val(matron.idPhotoSide);
        //工作/生活照
        str = '';
        let lifePhoto = matron.lifePhoto?.split(',')
        lifePhoto?.forEach(function (v){
            str += `<div class="layui-inline">
                        <img class="upImg" width="100" src="${v}">
                        <img class="closeUpload" src="../../img/close.png" data-id="lifePhoto">
                    </div>
                   `;
        });
        $("input[name='lifePhoto']").val(matron.lifePhoto);
        $("#lifePhoto").html(str);
        //技能证书
        str = '';
        let certificate = matron.certificate.split(',')
        certificate?.forEach(function (v){
            str += `<div class="layui-inline">
                        <img class="upImg" width="100" src="${v}">
                        <img class="closeUpload" src="../../img/close.png" data-id="certificate">
                    </div>
                   `;
        });
        $("input[name='certificate']").val(matron.certificate);
        $("#certificate").html(str);
        //体检报告
        str = '';
        let report = matron.report.split(',')
        report?.forEach(function (v){
            str += `<div class="layui-inline">
                        <img class="upImg" width="100" src="${v}">
                        <img class="closeUpload" src="../../img/close.png" data-id="report">
                    </div>
               `;
        });
        $("input[name='report']").val(matron.report);
        $("#report").html(str);
        //展示状态
        $('input[name="showStatus"]')?.each(function (k,v){
            if( $(v).val() == matron.showStatus ){
                $(v).attr('checked',true)
            }
        })

        form.render();
        closeUpload();
    }).catch(function (error) {
        layer.msg(error.msg)
    })


    //提交事件
    form.on('submit(submit)', function(data){
        //jazUserAuntDO 月嫂字段
        console.log(data,'表单')

        let params = {};

        params.jazUserAuntDO = {
            "id": checkId.id,
            "phone": data.field.phone, // 电话
            "projectId": data.field.type, // 项目类型
            "labelId": data.field.describe, // 多选标签
            "introduction": data.field.introduction, // 自我介绍
            "residentHome": data.field.residentHome, // 是否驻家
            "desireSalary": data.field.desireSalary, // 工资
            "workExperience" : data.field.workExperience, //  经验
            // "skill": data.field.skill, // 个人技能
            // "experience": data.field.experience, // 工作经历
            "auditResult" : null,
            "auditStatus" : 0,
            "inchPhoto": data.field.inchPhoto, // 寸照
            "idPhotoFront": data.field.idPhotoFront, // 身份证正面
            "idPhotoSide": data.field.idPhotoSide, // 身份证反面
            "lifePhoto": data.field.lifePhoto, // 工作/生活照
            "certificate": data.field.certificate, // 技能证书
            "report": data.field.report, // 体检报告
            "showStatus":data.field.showStatus, // 展示状态
            'serveTotal':data.field.serveTotal,
            'examinationCondition':data.field.examinationCondition,
            'nurseContent':data.field.nurseContent,
            'skill':data.field.skill

            // "skill":  JSON.stringify([{
            //     'serveTotal':data.field.serveTotal,
            //     'examinationCondition':data.field.examinationCondition,
            //     'nurseContent':data.field.nurseContent,
            //     'skill':data.field.skill
            // }])
        };

        //userDO 用户字段
        params.userDO = {
            "id":checkId.sysUserid,
            "name": data.field.name, //姓名
            "username": data.field.name,
            "orderPhone": data.field.phone, // 电话
            "mobile": data.field.phone,
            "nativePlace": data.field.nativePlace, // 籍贯
            "age": data.field.age, // 年龄
            "sex": data.field.sex, // 性别
            "zodiac": data.field.zodiac, // 生肖
            "constellation": data.field.constellation, // 星座
            "maritalStatus": data.field.maritalStatus, // 婚否
            "education": data.field.education, // 学历
            "height": data.field.height, // 身高
            "weight": data.field.weight, // 体重
            "detailedAddress": data.field.detailedAddress, // 现住址
            "province": data.field.province, // 省
            "city": data.field.city, // 市
            "district": data.field.district, // 区
            "type":1 // 用户类型
        };
        let hours = [];
        $(".parseInset").find('.startTime').each(function (k,v){
            hours.push({
                startTime:$(v).val(),
                endTime: $('.endTime').eq(k).val(),
                describe:$('.description').eq(k).val()
            })
        })

        if( checkId.type == 1 ){
            params.jazUserAuntDO.auditResult = 0;
            params.jazUserAuntDO.auditStatus = 1;
        }

        if( checkId.type == 2 ){
            params.jazUserAuntDO.auditResult = null;
            params.jazUserAuntDO.auditStatus = 0;
        }

        params.jazUserAuntDO.experience = JSON.stringify(hours)
        AjaxPost(prefix+'/updateUserAnut',params).then(function (response){
            parent.layer.msg("操作成功");
            var index = parent.layer.getFrameIndex(window.name); // 获取窗口索引
            parent.layer.close(index);
            parent.load();
        }).catch(error => {
            layer.msg(error.msg)
        })

    });

});

let contrast = '',  // 寸照
    idPhotoFront = '' , // 身份证正面
    idPhotoSide = '' , // 身份证反面
    photo = [] ,  // 工作/生活照
    certificate = [] , // 技能证书
    report = [] , //体检报告
    str = '';
function changBackfill(res,obj){

    // 添加图片之后展示在页面上
    if( obj.id == 'inchPhoto' ){
        str = '';
        str =  `
					<div class="layui-inline">
						<img class="upImg" src="${res.data}">
						<img class="closeUpload" src="../../img/close.png" data-id="inchPhoto">
					</div>
				`;
        $("#"+obj.id).html(str);
        $("input[name='inchPhoto']").val(res.data);
    }

    if( obj.id == 'idPhotoFront' ){
        str = '';
        str += `
				<div class="layui-inline">
					<img class="upImg" src="${res.data}">
					<img class="closeUpload" src="../../img/close.png" data-id="idPhotoFront">
				</div>
			`;
        $("#"+obj.id).html(str);
        $("input[name='idPhotoFront']").val(res.data);
    }


    if( obj.id == 'idPhotoSide' ){
        str = '';
        str += `
				<div class="layui-inline">
					<img class="upImg" src="${res.data}">
					<img class="closeUpload" src="../../img/close.png" data-id="idPhotoSide">
				</div>
			`;
        $("#"+obj.id).html(str);
        $("input[name='idPhotoSide']").val(res.data);
    }

    if( obj.id == 'lifePhoto' ){
        str = '';
        if( photo.length < obj.number ){
            photo.push(res.data);
            photo.forEach(function (v,k) {
                str += `
					<div class="layui-inline">
						<img class="upImg" src="${v}">
						<img class="closeUpload" data-index="${k}" src="../../img/close.png"  data-id="lifePhoto">
					</div>
				`;
            })
            $("#"+obj.id).html(str);
            $("input[name='lifePhoto']").val(photo.join(','));
        }
        else{
            layer.msg('上传的图片已达上限，请删除在传')
        }
    }

    if( obj.id == 'certificate' ){
        str = '';
        if( certificate.length < obj.number ){
            certificate.push(res.data);
            certificate.forEach(function (v,k) {
                str += `
					<div class="layui-inline">
						<img class="upImg" src="${v}">
						<img class="closeUpload" data-index="${k}" src="../../img/close.png" data-id="certificate">
					</div>
				`;
            })
            $("#"+obj.id).html(str);
            $("input[name='certificate']").val(certificate.join(','));
        }
        else{
            layer.msg('上传的图片已达上限，请删除在传')
        }
    }

    if( obj.id == 'report' ){
        str = '';
        if( report.length < obj.number ){
            report.push(res.data);
            report.forEach(function (v,k) {
                str += `
					<div class="layui-inline">
						<img class="upImg" src="${v}">
						<img class="closeUpload" data-index="${k}" src="../../img/close.png" data-id="report">
					</div>
				`;
            })
            $("#"+obj.id).html(str);
            $("input[name='report']").val(report.join(','));
        }
        else{
            layer.msg('上传的图片已达上限，请删除在传')
        }
    }

    closeUpload();
}

function closeUpload(){

    // 删除图片
    $(".closeUpload").unbind("click");
    $(".closeUpload").click(function (){
        console.log(11111)
        $(this).parents('.layui-inline').remove();
        let objId = $(this).attr('data-id');
        console.log(objId)
        if( objId == 'inchPhoto' ){
            $("input[name='inchPhoto']").val('');
        }

        if( objId == 'idPhotoFront' ){
            $("input[name='idPhotoFront']").val('');
        }

        if( objId == 'idPhotoSide' ){
            $("input[name='idPhotoSide']").val('');
        }

        if( objId == 'lifePhoto' ){
            photo.splice($(this).attr('data-index'),1);
            $("input[name='lifePhoto']").val(cardInfo.join(','));
        }

        if( objId == 'certificate' ){
            certificate.splice($(this).attr('data-index'),1);
            $("input[name='certificate']").val(cardInfo.join(','));
        }

        if( objId == 'report' ){
            report.splice($(this).attr('data-index'),1);
            $("input[name='report']").val(cardInfo.join(','));
        }

    })

}

